from rest_framework import viewsets, status
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.db.models import Q
from ..models import Character, CharacterTemplate
from ..serializers import CharacterListSerializers, CharacterDetailSerializers, CharacterCreateSerializers, CharacterUpdateSerializers, CharacterDeleteSerializers
from rest_framework.decorators import action

from common.core.response import success, error
from common.core.exceptions import SystemError
from common.core.constants import ErrorCode
from common.utils.db import atomic_transaction
from common.utils.logger import Logger
from common.core.paginations import CustomPagination


class CharacterListView(viewsets.ModelViewSet):
    """角色列表"""
    queryset = Character.objects.all()
    serializer_class = CharacterListSerializers
    search_fields = ['name', 'description']
    pagination_class = CustomPagination
    ordering_fields = ['created_at']
    
    @action(methods=['POST'], detail=False)
    @atomic_transaction
    def get_character_page(self, request):
        try:
            query_params = request.data.get('query_param', {})
            
            # 基础查询
            queryset = self.get_queryset().filter(is_deleted=False)
            
            filtered_queryset = self.filter_class(query_params, queryset=queryset).qs
            
            # 分页处理
            page = self.paginate_queryset(filtered_queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return success(data=self.paginator.get_paginated_data(serializer.data))
            
            serializer = self.get_serializer(filtered_queryset, many=True)
            return success(data=serializer.data)
        except Exception as e:
            Logger.error(f"查询折扣分页列表失败: {str(e)}")
            raise SystemError(detail="查询折扣分页列表失败", code=ErrorCode.SERVER_ERROR)

class CharacterDetailView(viewsets.ModelViewSet):
    """角色详情"""
    queryset = Character.objects.all()
    serializer_class = CharacterDetailSerializers
    lookup_field = 'id'
    lookup_url_kwarg = 'id'
    
    @action(methods=['POST'], detail=False)
    @atomic_transaction
    def get_character_by_id(self, request):
        try:
            character_id = request.data.get('id')
            instance = Character.objects.get(id=character_id, is_deleted=False)
            serializer = CharacterDetailSerializers(instance)
            return success(data=serializer.data)
        except Exception as e:
            Logger.error(f"查询角色详情失败: {str(e)}")
            raise SystemError(detail="查询角色详情失败", code=ErrorCode.SERVER_ERROR)

class CharacterCreateView(viewsets.ModelViewSet):
    """创建角色"""
    queryset = Character.objects.all()
    serializer_class = CharacterCreateSerializers

    @action(methods=['POST'], detail=False)
    @atomic_transaction
    def create_character(self, request):
        try:
            serializer = CharacterCreateSerializers(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return success(data=serializer.data)
            return error(data=serializer.errors, code=ErrorCode.INVALID_REQUEST)
        except Exception as e:
            Logger.error(f"创建角色失败: {str(e)}")
            raise SystemError(detail="创建角色失败", code=ErrorCode.SERVER_ERROR)

class CharacterUpdateView(viewsets.ModelViewSet):
    """更新角色"""
    queryset = Character.objects.all()
    serializer_class = CharacterUpdateSerializers
    lookup_field = 'id'
    lookup_url_kwarg = 'id' 
    
    @action(methods=['POST'], detail=False)
    @atomic_transaction
    def update_character(self, request):
        try:
            serializer = CharacterUpdateSerializers(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return success(data=serializer.data)    
            return error(data=serializer.errors, code=ErrorCode.INVALID_REQUEST)
        except Exception as e:
            Logger.error(f"更新角色失败: {str(e)}")
            raise SystemError(detail="更新角色失败", code=ErrorCode.SERVER_ERROR)

class CharacterDeleteView(viewsets.ModelViewSet):
    """删除角色"""
    queryset = Character.objects.all()
    serializer_class = CharacterDeleteSerializers
    lookup_field = 'id'
    lookup_url_kwarg = 'id'
    
    @action(methods=['POST'], detail=False)
    @atomic_transaction
    def delete_character(self, request):
        try:
            serializer = CharacterDeleteSerializers(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return success(data=serializer.data)
            return error(data=serializer.errors, code=ErrorCode.INVALID_REQUEST)
        except Exception as e:
            Logger.error(f"删除角色失败: {str(e)}")
            raise SystemError(detail="删除角色失败", code=ErrorCode.SERVER_ERROR)

